package calvin.study.rabbitmq.simple.simple_direct;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

public class Consumer {
	

	public static void main(String[] args) {
		new Thread(runnable, "simple_queuq1").start();
	}
	
	public static Runnable runnable = new Runnable() {
		@Override
		public void run() {
			// 创建连接工厂
			ConnectionFactory connectionFactory = new ConnectionFactory();
			connectionFactory.setHost("10.4.8.128");
			connectionFactory.setPort(5672);
			connectionFactory.setVirtualHost("test");

			final String queueName = Thread.currentThread().getName();
			Connection conn = null;
			Channel channel = null;
			try {
				// 创建连接
				conn = connectionFactory.newConnection("消费者");
				// 通过连接获取通道
				channel = conn.createChannel();

				// 消费者接收消息
				channel.basicConsume(queueName, true, new DeliverCallback() {
					@Override
					public void handle(String consumerTag, Delivery message) throws IOException {
						System.out.println(message.getEnvelope().getDeliveryTag());
						System.out.println(queueName + "收到的消息是：" + new String(message.getBody(), "UTF-8"));
					}
				}, new CancelCallback() {// 接收失败回调函数
					@Override
					public void handle(String consumerTag) throws IOException {
						System.out.println("消息接收失败");
					}
				});
				System.out.println(queueName + "开始接收消息");
			} catch (Exception e) {
			} finally {
				try {
					channel.close();
					conn.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (TimeoutException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	};

}
